package layouts;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;

import top.yunqisong.firstapp.R;

/**
 * 相对布局
 * Created by YunQisong on 2017/9/3.
 */

public class FrameLayoutActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_frame);
        FrameLayout frame = (FrameLayout) findViewById(R.id.frame_layout);
        final IconView icon = new IconView(FrameLayoutActivity.this);

        icon.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                //设置图标显示的位置
                icon.bitmapX = event.getX() - 150;
                icon.bitmapY = event.getY() - 150;
                //调用重绘方法
                icon.invalidate();
                return true;
            }
        });
        frame.addView(icon);
    }


    class IconView extends View {
        // 定义相关变量,依次是图标显示位置的X,Y坐标
        private float bitmapX;
        private float bitmapY;

        public IconView(Context context) {
            super(context);
            //设置图标的起始坐标
            bitmapX = 0;
            bitmapY = 200;
        }

        //重写View类的onDraw()方法
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            // 创建,并且实例化Paint的对象
            Paint paint = new Paint();
            // 根据图片生成位图对象
            Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.pic1);
            // 绘制图标
            canvas.drawBitmap(bitmap, bitmapX, bitmapY, paint);
            // 判断图片是否回收,木有回收的话强制收回图片
            if (bitmap.isRecycled()) {
                bitmap.recycle();
            }
        }
    }
}
